package com.znxs.zuopao_c.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.znxs.zuopao_c.common.BaseResponse;
import com.znxs.zuopao_c.common.ErrorCode;
import com.znxs.zuopao_c.common.ResultUtils;
import com.znxs.zuopao_c.exception.BusinessException;
import com.znxs.zuopao_c.job.PreCacheJob;
import com.znxs.zuopao_c.domain.Request.UserLoginRequest;
import com.znxs.zuopao_c.domain.Request.UserRegisterRequest;
import com.znxs.zuopao_c.domain.User;
import com.znxs.zuopao_c.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.znxs.zuopao_c.contant.userContant.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 * @author znxs
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户中心接口")
@Slf4j
//@CrossOrigin(originPatterns = {"http://localhost:5173"})
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private PreCacheJob preCacheJob;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private final List<Long> MAIN_LIST = Arrays.asList(1L,2L,3L,4L);

    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user,HttpServletRequest request) {
        // 非空校验
        if (user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        Boolean result = userService.updateUser(user,loginUser);
        return ResultUtils.success(result);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String plantCode = userRegisterRequest.getPlantCode();
        // controller 校验倾向于请求本身的校验，不涉及业务逻辑
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, plantCode)) {
            return ResultUtils.error(ErrorCode.NULL_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(), userRegisterRequest.getCheckPassword(), plantCode);
        return ResultUtils.success(result);
    }


    @GetMapping("/current")
    public BaseResponse<User> getCurrent(HttpServletRequest request) {
        // 获取用户的状态
        User userObj = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        Long id = userObj.getId();
        // todo 校验用户是否合法
        User user = userService.getById(id);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // controller 校验倾向于请求本身的校验，不涉及业务逻辑
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);

    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userOutLogin(HttpServletRequest request) {
        userService.outLogin(request);
        return ResultUtils.success("退出登录成功");
    }


    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(@RequestParam(value = "username", required = false) String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "不为管理员");
        }
        // 搜索操作
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 不为空时在模糊查询
        if (StringUtils.isNotBlank(username)) {
            userQueryWrapper.like("username", username);
        }
        List<User> userList = userService.list(userQueryWrapper);
        List<User> safeUserList = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(safeUserList);
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUser(@RequestParam(required = false,defaultValue = "10") long pageSize,@RequestParam(required = false,defaultValue = "1")long pageNum,HttpServletRequest request) {
        User loginUser = userService.isLogin(request);
        String redisKey;
        if (loginUser==null){
            redisKey = String.format("yupao:user:recommend:%s", MAIN_LIST.get(0));
        }else {
            redisKey = String.format("yupao:user:recommend:%s", loginUser.getId());
        }
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);

        if (userPage != null) {
            return ResultUtils.success(userPage);
        }
        // 无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        // 写缓存
        try {
            valueOperations.set(redisKey, userPage, 1000000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return ResultUtils.success(userPage);

    }

    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestParam long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "不为管理员");
        }
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 删除操作
        return ResultUtils.success(userService.removeById(id));
    }

    /**
     * 根据提供的tag搜索用户
     *
     * @param tagNameList tags名称列表
     * @return 用户列表
     */
    @GetMapping("/search/tags")
    @ApiOperation("根据tag搜索用户")
    public BaseResponse<List<User>> searchUserByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.searchUserByTags(tagNameList);
        return ResultUtils.success(users);
    }

    @GetMapping("/list/match/{num}")
    public BaseResponse<List<User>> matchUsers(@PathVariable("num")Long num,HttpServletRequest request){
        if (num<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 如果用户登录了，查看是否有缓存
        String redisKey = String.format("zuopao:user:match:%s",loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 如果有缓存 读缓存
        List<User> userList = (List<User>)valueOperations.get(redisKey);
        if (CollectionUtils.isNotEmpty(userList)){
            return ResultUtils.success(userList);
        }
        // 如果没有缓存 直接获取数据 做缓存
        List<User> matchUsers = userService.matchUsers(num, loginUser);
        if (matchUsers.isEmpty()){
            throw new BusinessException(ErrorCode.SYS_ERROR);
        }
        // 写缓存
        try {
            valueOperations.set(redisKey,matchUsers, 1000000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return ResultUtils.success(matchUsers);
    }

}
